package com.ifacebox.face.track.ui;

import com.github.sarxos.webcam.Webcam;
import com.ifacebox.face.track.sevice.FaceEnginePooledService;
import com.ifacebox.face.track.utils.ThreadUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.List;
import java.util.Objects;

/**
 * @author znn
 */
public class FaceTrackToolBar extends JToolBar implements ActionListener, ItemListener {
    private static final ImageIcon ADD_USER_ICON = new ImageIcon(Objects.requireNonNull(FaceTrackToolBar.class.getResource("/man.png")));
    private static final ImageIcon SETTING_ICON = new ImageIcon(Objects.requireNonNull(FaceTrackToolBar.class.getResource("/setting.png")));
    private final JButton addFaceUser, faceConfig;
    private final FaceUserDialog faceUserDialog;
    private final FaceConfigDialog faceConfigDialog;
    private final FaceWebCamPanel faceWebCamPanel;
    private FaceWebCamPicker faceWebCamPicker;
    private Webcam webCam;

    public FaceTrackToolBar(JFrame owner, List<Webcam> webCams, FaceEnginePooledService.FaceEnginePool faceDetectPool, FaceWebCamPanel faceWebCamPanel) {
        this.faceWebCamPanel = faceWebCamPanel;
        this.faceUserDialog = new FaceUserDialog(owner, faceDetectPool);
        this.faceConfigDialog = new FaceConfigDialog(owner);
        super.setFloatable(false);
        super.setLayout(new FlowLayout(FlowLayout.LEFT));
        super.add(this.addFaceUser = new JButton(ADD_USER_ICON) {{
            this.addActionListener(FaceTrackToolBar.this);
        }});
        super.add(this.faceConfig = new JButton(SETTING_ICON) {{
            this.addActionListener(FaceTrackToolBar.this);
        }});
        super.addSeparator();
        if (webCams != null && !webCams.isEmpty()) {
            super.add(this.faceWebCamPicker = new FaceWebCamPicker(webCams) {{
                this.addItemListener(FaceTrackToolBar.this);
            }});
            this.webCam = this.faceWebCamPicker.getSelectedWebcam();
            this.faceWebCamPanel.start(this.webCam);
        }
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getSource() == this.faceWebCamPicker) {
            if (e.getItem() != this.webCam) {
                this.webCam = this.faceWebCamPicker.getSelectedWebcam();
                this.faceWebCamPanel.stop();
                this.faceWebCamPanel.start(this.webCam);
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == this.addFaceUser) {
            ThreadUtils.runThread(this.faceUserDialog::refresh);
            this.faceUserDialog.setVisible(true);
        }
        if (e.getSource() == this.faceConfig) {
            this.faceConfigDialog.setVisible(true);
        }
    }
}
